package com.cy.mall.service.comm.impl;

import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.cy.mall.comm.utils.TencentApiSignUtils;
import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.model.Result;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.comm.FaceIDCertificateService;

import lombok.extern.slf4j.Slf4j;

/**
 * FaceID人脸身份验证Service
 *
 * @author tanyilin
 *
 * @create 2019年2月21日 下午3:38:26
 */
@Slf4j
@Service
public class FaceIDCertificateServiceImpl extends BaseService implements FaceIDCertificateService {
	
	@Value("${face-id.secret.id}")
	private String secretId;
	
	@Value("${face-id.secret.key}")
	private String secretKey;
	
	@Value("${face-id.redirect.url}")
	private String redirectUrl;
	
	@Autowired
	private RestTemplate restTemplate;

	private HttpEntity httpEntity;
	
	@PostConstruct
	public void init() {
		//设置header
		HttpHeaders headers = new HttpHeaders();
		headers.add("Host", "faceid.tencentcloudapi.com");
		headers.add("Content-Type", "application/x-www-form-urlencoded");
		httpEntity = new HttpEntity(null, headers);
	}
	
	@Override
	public Result<Map<String, Object>> getBizToken() {
		
		//设置参数，使用 TreeMap 可以自动排序
		TreeMap<String, Object> params = new TreeMap<>();
		//公共参数
		params.put("Action", "DetectAuth");
		params.put("SecretId", secretId);
		params.put("Timestamp", System.currentTimeMillis() / 1000);
		params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE));
		params.put("Version", "2018-03-01"); 
        params.put("Region", "ap-guangzhou"); 
		params.put("RuleId", "0");
		//业务参数
		params.put("RedirectUrl", redirectUrl);
		// 公共参数 ：签名
		String stringToSign = TencentApiSignUtils.getStringToSign(params, "GET", "faceid.tencentcloudapi.com");
		String signature = "";
		try {
			signature = TencentApiSignUtils.sign(stringToSign, secretKey, "HmacSHA1");
		} catch (Exception e) {
			log.error("请求 获取 biz_token、url 接口 DetectAuth 时，签名异常 ", e);
			return Result.fail("请求 获取 biz_token、url 接口 DetectAuth 时，签名异常 ");
		}
		//设置签名参数
		params.put("Signature", signature); 
		
		//拼接得到url
		String url = TencentApiSignUtils.getUrl(params, "https://faceid.tencentcloudapi.com");
		
		log.info("请求 获取 biz_token、url 接口 DetectAuth， URL = {}", url);
		
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
		
		if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            return Result.fail("请求 获取 biz_token、url 接口 DetectAuth 失败");
        }
		
		log.info("请求 获取 biz_token、url 接口 DetectAuth，回调报文：{}", responseEntity.getBody());
		
		Map<String, Object> responseBodyMap = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
		
		Object responseMap = responseBodyMap.get("Response");
		if(responseMap == null) {
			return Result.fail("请求 获取 biz_token、url 接口 DetectAuth 失败");
		}
		
		Map<String, Object> dataMap = (Map<String, Object>) responseMap;
		
		Object error = dataMap.get("Error");
		if(error != null) {
			return Result.fail("请求 获取 biz_token、url 接口 DetectAuth 失败");
		}
		
		return Result.success("请求 获取 biz_token、url 接口 DetectAuth 成功", dataMap);
	}

	@Override
	public Result<Map<String, Object>> getResult(String bizToken) {
		
		//设置参数，使用 TreeMap 可以自动排序
		TreeMap<String, Object> params = new TreeMap<>();
		//公共参数
		params.put("Action", "GetDetectInfo");
		params.put("SecretId", secretId);
		params.put("Timestamp", System.currentTimeMillis() / 1000);
		params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE));
		params.put("Version", "2018-03-01"); 
        params.put("Region", "ap-guangzhou"); 
        params.put("RuleId", "0");
		//业务参数
        params.put("BizToken", bizToken);
        params.put("InfoType", "1");
        
        // 公共参数 ：签名
 		String stringToSign = TencentApiSignUtils.getStringToSign(params, "GET", "faceid.tencentcloudapi.com");
 		String signature = "";
 		try {
			signature = TencentApiSignUtils.sign(stringToSign, secretKey, "HmacSHA1");
		} catch (Exception e) {
			log.error("请求 获取验证结果信息 接口 GetDetectInfo 时，签名异常 ", e);
			return Result.fail("请求 获取验证结果信息 接口 GetDetectInfo 时，签名异常 ");
		}
		//设置签名参数
		params.put("Signature", signature); 
		
		//拼接得到url
		String url = TencentApiSignUtils.getUrl(params, "https://faceid.tencentcloudapi.com");
		
		log.info("请求 获取验证结果信息 接口 GetDetectInfo， URL = {}", url);
		
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
		
		if (!HttpStatus.OK.equals(responseEntity.getStatusCode())) {
            return Result.fail("请求 获取验证结果信息 接口 GetDetectInfo 失败");
        }
		
		log.info("请求 获取验证结果信息 接口 GetDetectInfo，回调报文：{}", responseEntity.getBody());
 		
		Map<String, Object> responseBodyMap = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
		
		Object responseMap = responseBodyMap.get("Response");
		if(responseMap == null) {
			return Result.fail("请求 获取验证结果信息 接口 GetDetectInfo 失败");
		}
		
		Map<String, Object> dataMap = (Map<String, Object>) responseMap;
		
		Object error = dataMap.get("Error");
		if(error != null) {
			return Result.fail("请求 获取验证结果信息 接口 GetDetectInfo  失败");
		}
		
		return Result.success("请求 获取验证结果信息 接口 GetDetectInfo 成功", dataMap);
	}

	

	
}
